package com.dangdang.action.authorize;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;


import com.dangdang.action.BaseAction;
import com.dangdang.util.Constants;
import com.dangdang.util.NumberUtils;
import com.googlecode.jsonplugin.annotations.JSON;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 图片验证码控制层
 * 
 * @author Wangpeihu
 * @team [Never give up]
 * @since JDK1.6(建议)
 * @date 2010-1-26
 */
public class NumberAction extends BaseAction {
	private String number;

	private InputStream checkStream;

	private boolean ok;

	@JSON(serialize = false)
	public InputStream getCheckStream() {
		return checkStream;
	}

	public void setCheckStream(InputStream checkStream) {
		this.checkStream = checkStream;
	}

	@JSON(serialize = false)
	public String getNumber() {
		return number;
	}

	public void setNumber(String number) {
		this.number = number;
	}

	public boolean isOk() {
		return ok;
	}

	public String generate() throws Exception {
		Map<String, BufferedImage> map = NumberUtils.generate();

		Iterator<String> it = map.keySet().iterator();

		if (it.hasNext()) {
			String number = it.next();
			BufferedImage image = map.get(number);
			session.put(Constants.NUMBER_KEY, number);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(baos);
			encoder.encode(image);
			byte[] arry = baos.toByteArray();
			checkStream = new ByteArrayInputStream(arry);
			return "success";
		}
		return null;
	}

	public String check() throws Exception {
		ok = number.equals(session.get(Constants.NUMBER_KEY));
		return "success";
	}

	public void setOk(boolean ok) {
		this.ok = ok;
	}
}
